package org.example.leetcode.interview.greed;

public class LC0053 {
    /**
     * 贪心, 求子串最大和.
     * 遍历整个数组累加得和, 题目要求最大和所以当counter小于等于0时就重置
     * @param nums
     * @return
     */
    public int maxSubArray(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }

        int sum = Integer.MIN_VALUE;
        int counter = 0;
        for (int i = 0; i < nums.length; i++) {
            counter += nums[i];
            sum = Math.max(sum, counter);
            if (counter <= 0) {
                counter = 0;
            }
        }

        return sum;
    }
}
